package org.nf.web.servlet.view;

import com.google.gson.*;
import org.nf.web.servlet.BaseView;
import org.nf.web.servlet.ServletApi;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author wangl
 * @date 2021/5/28
 * Json视图
 */
public class JsonView extends BaseView {

    private final Object data;

    private final GsonBuilder gsonBuilder;

    public JsonView(Object data) {
        this.data = data;
        gsonBuilder = new GsonBuilder();
    }

    public void setDateFormat(String pattern) {
        gsonBuilder.setDateFormat(pattern);
        //构建LocalDateTime的json序列化器
        JsonSerializer<LocalDateTime> localDateTimeJsonSerializer = (localDateTime, type, jsonSerializationContext) ->
                new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern(pattern)));
        gsonBuilder.registerTypeAdapter(LocalDateTime.class, localDateTimeJsonSerializer);
        //构建LocalDate的json序列化器
        JsonSerializer<LocalDate> localDateJsonSerializer = (localDate, type, jsonSerializationContext) ->
                new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern(pattern)));
        gsonBuilder.registerTypeAdapter(LocalDate.class, localDateJsonSerializer);
        //构建LocalTime的json序列化器
        JsonSerializer<LocalTime> localTimeJsonSerializer = (localTime, type, jsonSerializationContext) ->
                new JsonPrimitive(localTime.format(DateTimeFormatter.ofPattern(pattern)));
        gsonBuilder.registerTypeAdapter(LocalTime.class, localTimeJsonSerializer);
    }

    @Override
    protected void render(ServletApi api) throws IOException {
        HttpServletResponse response = api.response();
        response.setContentType("application/json;charset=utf-8");
        String json = gsonBuilder.create().toJson(data);
        response.getWriter().println(json);
    }
}
